﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using TwKarma.Logic.Template;

namespace TwKarma.Web.App.Parts
{
	public class Render : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			Response.Clear();

			if (Request.QueryString["What"] == null)
				return;

			switch (Request.QueryString["What"].ToLowerInvariant())
			{
				case "karmarecieved":
					Response.Write(RenderKarmaRecieved(Request.QueryString["For"]));
					break;
				case "karmasent":
					Response.Write(RenderKarmaSent(Request.QueryString["For"]));
					break;
				case "karmaglobal":
					Response.Write(RenderKarmaGlobal());
					break;
					
			}
		}

		private string RenderKarmaRecieved(string screenname)
		{
            Renderable thing = Store.Get(Server.MapPath("~/content/templates/karmarecieveditem.html"));

            KarmaService.Votes service = new KarmaService.Votes();
            KarmaService.KarmaVote[] votes = service.UserRecieved(screenname, 1, 5);

			return RenderKarmaVotes(thing, votes);
		}
				
		private string RenderKarmaSent(string screenname)
		{
			Renderable thing = Store.Get(Server.MapPath("~/content/templates/karmasentitem.html"));

			KarmaService.Votes service = new KarmaService.Votes();
			KarmaService.KarmaVote[] votes = service.UserSent(screenname, 1, 5);
						
			return RenderKarmaVotes(thing, votes);
		}

		private string RenderKarmaGlobal()
		{
			Renderable thing = Store.Get(Server.MapPath("~/content/templates/karmarecieveditem.html"));

			KarmaService.Votes service = new KarmaService.Votes();
		
            StringBuilder html = new StringBuilder();
            foreach (KarmaService.Tweet tweet in service.Global(1, 10))
                thing.Render(html, tweet);

            return html.ToString();
        }

		private static string RenderKarmaVotes(Renderable thing, KarmaService.KarmaVote[] votes)
		{
			StringBuilder html = new StringBuilder();
			foreach (KarmaService.KarmaVote vote in votes)
				thing.Render(html, vote);

			return html.ToString();
		}
	}
}